package eva

import (
	"context"
	"trusteva/app/eva/internal/ruleutil"
	"trusteva/app/eva/model"

	"trusteva/app/eva/internal/svc"
	"trusteva/app/eva/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateRuleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateRuleLogic {
	return &UpdateRuleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateRuleLogic) UpdateRule(req *types.UpdateRuleRo) (resp *types.UpdateRuleRsp, err error) {
	var m = model.Rule{
		AppId:    req.AppId,
		DeviceId: req.DeviceId,
		DstIP:    req.DstIP,
		DstPort:  req.DstPort,
		Status:   req.Status,
	}

	rules, err := ruleutil.ParseRules(m)
	if err != nil {
		return nil, err
	}

	// 删除旧规则
	{
		var old model.Rule
		err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", req.Id).First(&old).Error
		if err != nil {
			return nil, err
		}
		rules, _ := ruleutil.ParseRules(old)
		for _, v := range rules {
			_, err = l.svcCtx.RedisClient.SremCtx(l.ctx, v.Key())
			if err != nil {
				return nil, err
			}
		}
	}

	// 添加新规则
	{
		err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", req.Id).
			Select("AppId", "DeviceId", "DstIP", "DstPort", "Status").
			Updates(&m).Error
		if m.Status == model.RulePass {
			for _, v := range rules {
				_, err = l.svcCtx.RedisClient.SaddCtx(l.ctx, v.Key())
				if err != nil {
					return nil, err
				}
			}
		}
	}

	return
}
